/*
 * 问答、系统消息、私聊
 */

/*
 * ====================================================
 * 问答、系统消息、私聊
 */
$(function(){
	
	Scheduler.addEventHandler(EVENT.qa, qaHandler);//加载问答的任务回调处理器
	
	$("#newAllqaCount").hide();
	$("#newMyqaCount").hide();
	$("#myQaTab").bind("click", clickMyQaTab);//TODO：改成touch事件
	$("#allQaTab").bind("click", clickAllQaTab);//TODO：改成touch事件
	$("#qaForm").bind("submit", commitMsg);
	
});

function loadMsg(array){
	info("receive msg array:", array);
	if(!array || array.length==0)return;
	for(var i in array){
		var msg = array[i];
		if("publicMsg" == msg.type){
			appendSysMsg(msg.content);
		}else if("chat" == msg.type){
			receiveChat({talkerId:msg.senderid, talkerName:msg.sender, msg:msg.content});
		}else{
			warn("the type of msg is unknown:", msg.type);
		}
	}
}

var QA = {
		newMyqaCount: 0,
		newAllqaCount: 0
	};

//装载一次问答数据：
//{inittimestamp:inittimestamp, qaArray：[{question:question,questionower:questionower,questiontimestamp:questiontimestamp,answer:answer,answertimestamp:answertimestamp}]}
function loadQA(data){
	info("[ipad-live][loadQA]--------------------load qa data-----------------",data);
	var qadatas = data.qaArray;
	var baseTime = data.inittimestamp;
	PAGEATTR.playbasetime = baseTime;
	for(i in qadatas){
		var qa = qadatas[i];
		if(qa.removed==true || qa.removed=="true"){//执行删除命令，不考虑命令先于任务装载的情况
			Scheduler.removeDurationTask(compareQa, qa, EVENT.qa);
			removeQaEle(qa.questionid);
			continue;//已删除
		}
		if(qa.starttimestamp <= PAGEATTR.playbasetime){//历史问答直接加载
			appendQa(data);
			continue;
		}
		appendQaTask(qa);
	}
}

//删除某一问答（我的问答和所有问答）
function removeQaEle(qaId){
	var eles = $("dl[name="+qaId+"]");
	if(eles.length!=0){
		eles.remove();
		info("[ipad-live][removeQaEle] remove qa:"+qaId);
		return true;
	}else{
		return false;
	}
}

function compareQa(data1, data2){
	if(data1.questionid == data2.questionid)return true;
	return false;
}

//添加一个问答调度任务
function appendQaTask(qadata){
	var startValue = playingTime(qadata.publishtimestamp, PAGEATTR.playbasetime);
	endValue = startValue + 60*60*1000;
	Scheduler.addDurationTask(startValue, endValue, EVENT.qa, qadata);
}

//问答回调处理器（供调度器任务回调）
function qaHandler(data){
	appendQa(data);
}

//加载一个问答
function appendQa(qa){
	if(isCurrentUser(qa.questionowner)){
		if(typeof qa.answer == "string" && $.trim(qa.answer).length > 0){
			debug("[ipad-live][appendQa] typeof qa.answer:"+typeof qa.answer+",$.trim(qa.answer).length:"+$.trim(qa.answer).length);
			info("[ipad-live][appendQa] append my qa:",qa);
			appendMyqa(qa);
		}
	}
	appendAllqa(qa);
	flushNewQaCount();
}

function isCurrentUser(nickname){
	return typeof PAGEATTR.nickname == "string" && PAGEATTR.nickname == nickname;
}

function appendMyqa(qa){
	addQa(qa, "qaMyList");
	QA.newMyqaCount += 1;
}

function appendAllqa(qa){
	addQa(qa, "qaAllList");
	QA.newAllqaCount += 1;
}

//加载一个系统消息
function appendSysMsg(msg){
	info("[ipad-live][appendSysMsg] begin appending system message:", msg);
	var ele1 = createSysMsgEle(msg);
	var ele2 = createSysMsgEle(msg);
	$("#qaMyList").append(ele1);
	$("#qaAllList").append(ele2);
	QA.newMyqaCount += 1;
	QA.newAllqaCount += 1;
	flushNewQaCount();
}

function commitMsg(){
	var talkto = currTalketo();
	if(typeof talkto  == "undefined" || talkto == "undefined" || talkto ==""){
		commitQa();
	}else{
		commitChat(talkto);
	}
	return false;
}

function beforeQaSubmit(){
	var question = $.trim($("#qaText").val());
	if(question.length==0){
		alert(iPadLang.contentCannotEmpty);
		return false;
	}else if(question.length>140){
		alert(iPadLang.contentMoreThan140Chr);
		return false;
	}
	if(!VIDEO.isStarted){
		alert(iPadLang.pleasePalyVideo);
		return false;
	}
	return true;
}

//提交问题
function commitQa(){
	if(!beforeQaSubmit())return false;
	var qa = createMyQaSubmit();
	if(typeof submitQuestion == "function"){
		try{
			submitQuestion(qa);//外部接口
			appendQuestion(qa);
		}catch(e){
			console.error("[ipad-live][commitQa] question submit exception:");
			console.error(e);
		}
	}else{
		console.error("[ipad-live][commitQa] 未定义函数submitQuestion()!");
	}
	$("#qaText").val("");
	return false;
}

function createMyQaSubmit(){
	var qa = {};
	qa.question = $.trim($("#qaText").val());
	qa.questionowner=PAGEATTR.nickname;
	qa.questiontimestamp = new Date().getTime() /1000;//秒
	return qa;
	
}

function appendQuestion(qa){
	var ele = createQaEle(qa);
	ele.addClass("unPush");
	$("#qaMyList").append(ele);
	QA.newMyqaCount += 1;
	flushNewQaCount();
}

//刷新新问答计数（需要隐藏时将count值置为0即可。每次展示变化时，记得调用本方法）。
function flushNewQaCount(){
	if($("#qaView").hasClass("askCurrent1")){
		QA.newMyqaCount = 0;
	}else{
		QA.newAllqaCount = 0;
	}
	showCount("newMyqaCount", QA.newMyqaCount);
	showCount("newAllqaCount", QA.newAllqaCount);
}

//显示新问答计数（值为0时将其隐藏）
function showCount(id, count){
	if(typeof count!="number"){
		console.error("showCount.count is not a number:"+typeof count);
	}
	if(count==0){
		$("#"+id).hide();
	}else if(count<10){
		$("#"+id).text(count);
		$("#"+id).show();
	}else if(count>=10){
		$("#"+id).text("N");
		$("#"+id).show();
	}else{
		console.error("showCount.count value error:"+ count);
	}
}

//添加问答信息到某一列表（我的问答和所有问答列表）
function addQa(qa,toList){
	var ele = createQaEle(qa);
	$("#"+toList).append(ele);
}

//创建一个问答页面元素
function createQaEle(qa){
	if(typeof qa.questionowner!="string") qa.questionowner = "";
	if(typeof qa.answerowner!="string") qa.answerowner = "";
	var sEle = '<dl class="askList" name="'+qa.questionid+'">';
	sEle += '<dd class="q">'+ qa.question +'<p class="sign">- '+qa.questionowner;
	var qTime = showTime4Second(qa.questiontimestamp);
	if(qTime!=null) sEle += ' ('+qTime+')';
	sEle +='</p></dd>';
	if(typeof qa.answer == "string" && $.trim(qa.answer).length > 0){
		sEle += '<dd class="a">'+ qa.answer +'<p class="sign">- '+qa.answerowner;
		var aTime = showTime4Second(qa.answertimestamp);
		if(aTime!=null)sEle += ' ('+aTime+')';
		sEle +='</p></dd>';
	}
	sEle += '</dl>';
	return $(sEle);
}

function showTime4Second(sec){
	if(typeof sec != "number" && typeof sec != "string")return null;
	return showTime4Misec(Number(sec)*1000);
}

function showTime4Misec(misec){
	if(typeof misec != "number" && typeof misec != "string")return null;
	var d = new Date();
	d.setTime(Number(misec));
	return formatDate(d,"HH:mm:ss");
}

//创建一个系统消息页面元素
function createSysMsgEle(msg){
	return $('<dl class="systemSmg"><dt class="smg">'+iPadLang.systemMessagePrefix+'</dt><dd>'+ msg +'</dd></dl>');
}

//展示我的问答
function clickMyQaTab(){
	changeQaTab("qaView","askCurrent1","askCurrent2");
	QA.newMyqaCount = 0;
	flushNewQaCount();
}

//展示所有问答
function clickAllQaTab(){
	changeQaTab("qaView","askCurrent2","askCurrent1");
	QA.newAllqaCount = 0;
	flushNewQaCount();
}

//问答列表切换时改变样式
function changeQaTab(divId, addClass, removeClass ){
	$("#"+divId).removeClass(removeClass);
	$("#"+divId).addClass(addClass);
}